// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

package com.fowo.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.Supplier;
import com.fowo.api.entity.SupplierFlowNode;
import com.fowo.api.entity.SupplierReview;
import com.fowo.api.model.supplier.SupplierVo;
import com.fowo.api.model.supplier.review.SupplierReviewVo;
import com.fowo.api.model.supplier.task.instance.SupplierTaskInstanceVo;
import com.fowo.api.service.SupplierReviewService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysBase;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 供应商评审 服务实现类
 */
@Service
@Slf4j
public class SupplierReviewServiceImpl extends SupplierReviewBaseServiceImpl implements SupplierReviewService {

    @Resource
    private SupplierFlowNodeServiceImpl supplierFlowNodeService;
    @Resource
    private SupplierTaskInstanceServiceImpl supplierTaskInstanceService;
    @Resource
    private SupplierServiceImpl supplierService;

    @DataActivity(action = SysDataActivityAction.Add)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(SupplierReviewVo model) throws Exception {
        Assert.isTrue(ObjUtil.isNotEmpty(model), "参数异常!");
        try {
            SupplierFlowNode node = supplierFlowNodeService.getNode(model.getEnCode(),null);
            Long id = super.create(model);
            model.setId(id);
            supplierFlowNodeService.process(CollUtil.newArrayList(model), node, node.getNode(),null, item -> {
            });
            return id;
        } catch (Exception ex) {
            log.error("发生异常,异常信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
            throw new RuntimeException("发生异常,信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
        }
    }

    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了提交操作"
    )
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void doSubmit(List<Long> ids) throws Exception {
        Assert.isTrue(CollUtil.isNotEmpty(ids), "参数异常!");
        List<SupplierReview> list = this.listByIds(ids);
        SupplierFlowNode node = supplierFlowNodeService.getConditionNode(list);
        supplierFlowNodeService.process(list, node, node.getNode(), CollUtil.newArrayList(node.getNodeUp()), item -> {
        });
        this.updateBatchById(list);
    }

    /**
     * 取消提交
     */
    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了取消提交操作"
    )
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unDoSubmit(List<Long> ids) throws Exception {
        Assert.isTrue(CollUtil.isNotEmpty(ids), "参数异常!");
        List<SupplierReview> list = this.listByIds(ids);
        SupplierFlowNode node = supplierFlowNodeService.getConditionNode(list);
        supplierFlowNodeService.process(list, node, node.getNodeExceptionStatus(), CollUtil.newArrayList(node.getNodeUp()), item -> {
            Assert.isTrue(StrUtil.isNotBlank(node.getNodeExceptionStatus()), "没有配置异常节点!");
        });
        this.updateBatchById(list);
    }


    /**
     * 转正
     */
    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了转正操作"
    )
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void doPass(List<Long> ids) throws Exception {
        Assert.isTrue(CollUtil.isNotEmpty(ids), "参数异常!");
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Assert.isTrue(ObjUtil.isNotEmpty(currentUser), "请先登录!");
        List<SupplierReview> list = this.listByIds(ids);
        SupplierFlowNode node = supplierFlowNodeService.getConditionNode(list);
        supplierFlowNodeService.process(list, node, node.getNode(), CollUtil.newArrayList(node.getNodeUp()), item -> {
            item.setDoUser(CollUtil.newArrayList(currentUser.getUserId()));
            item.setDoTime(new Date());
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getSupplierCode, item.getEnterpriseId()),false);
            Assert.isTrue(ObjUtil.isEmpty(supplier), "供应商重复开发:{}请检查!", item.getEnterpriseId());
            SupplierTaskInstanceVo supplierTaskInstanceVo = supplierTaskInstanceService.getVoById(item.getInstanceId());
            Assert.isTrue(ObjUtil.isNotEmpty(supplierTaskInstanceVo), "供应商未开发,请检查!");
            SupplierVo model = BeanUtil.copyProperties(supplierTaskInstanceVo, SupplierVo.class, Arrays.stream(ReflectUtil.getFields(SysBase.class)).map(m -> ReflectUtil.getFieldName(m)).toArray(String[]::new));
            if (StrUtil.isNotBlank(item.getEnterpriseId())){
                model.setSupplierCode(item.getEnterpriseId());
            }
            if (StrUtil.isNotBlank(item.getEnterpriseName())){
                model.setSupplierName(item.getEnterpriseName());
            }
            model.setStatus("0");
            model.setRemarks(StrUtil.format("{}通过评审任务:{}转正", DateUtil.now(), item.getReviewId()));
            try {
                supplierService.create(model);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        this.updateBatchById(list);
    }
}
